#' TitanCNA_getAllModel.R
#' author: Xianfeng Xu 
#' NJMU
#' contact: <xuxianfeng@njmu.edu.cn>
#' date:	  August 2, 2021

library(optparse)
library(stringr)
library(data.table)
library(dplyr)

option_list <- list(
  make_option(c("--input_file"), type = "character", help = ""),
  make_option(c("--outFile"), type = "character", help = "")
)


if(1!=1){
	tumor <- "TL2334"
	input_file <- paste0("/public/home/xxf2019/20220205_lungSomatic/results_titanCNA/titan/doubleCheck/",tumor,"/",tumor,"_allModel_params.abstarct.tsv")
	outFile <- paste0("/public/home/xxf2019/20220205_lungSomatic/results_titanCNA/titan/doubleCheck/",tumor,"/",tumor,".minSDBW.txt")
}

parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)

input_file <- opt$input_file
outFile <- opt$outFile

dat <- fread(input_file)

tmp <- dat %>%
group_by(id) %>%
summarize( Phi = Phi[which.max(loglik_revise)] , loglik_revise = max(loglik_revise) )

## 四倍体明确
## 若loglikehood均选择四倍体,且sdbw最小的也在四倍体，选择四倍体

## 四倍体含糊
## 只在二倍体和三倍体按照loglik在不同的cluster的最小值分布确定倍体，在选择sdbw最小的


if(length(unique(tmp$Phi))!=1){

	dat <- subset( dat , Phi != 4 )

	tmp <- dat %>%
	group_by(id) %>%
	summarize( Phi = Phi[which.max(loglik_revise)] , loglik_revise = max(loglik_revise) )

	ploidySolInd <- as.numeric(names(which.max(table(tmp$Phi))))

	tmp <- subset( dat , Phi==ploidySolInd )
	res <- tmp[which.min(tmp$sdbw),]

}else{
	res <- dat[which.min(dat$sdbw),]
}

#outFile <- paste0(basename(outDir), ".txt")
write.table(res, file = outFile, col.names = T, row.names = F, quote = F, sep = "\t")
#close(fc)
